package com.changcheng.project.handsetinfo.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.changcheng.common.exception.BusinessExceptionZ;
import com.changcheng.common.utils.StringUtils;
import com.changcheng.project.yuminsi.vo.BaseOutput;
import org.springframework.util.CollectionUtils;
import com.changcheng.project.handsetinfo.vo.HandSetRequest;
import com.changcheng.project.yuminsi.commons.RestTemplateHandheld;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.changcheng.framework.aspectj.lang.annotation.Log;
import com.changcheng.framework.aspectj.lang.enums.BusinessType;
import com.changcheng.project.handsetinfo.domain.AHandsetInfo;
import com.changcheng.project.handsetinfo.service.IAHandsetInfoService;
import com.changcheng.framework.web.controller.BaseController;
import com.changcheng.framework.web.domain.AjaxResult;
import com.changcheng.common.utils.poi.ExcelUtil;
import com.changcheng.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 手持机管理Controller
 *
 * @author dazhi
 * @date 2020-11-17
 */
@SuppressWarnings("all")
@Controller
@RequestMapping("/handsetinfo/handsetinfo")
public class AHandsetInfoController extends BaseController {
    private String prefix = "handsetinfo/handsetinfo";

    @Autowired
    private IAHandsetInfoService aHandsetInfoService;

    @Autowired
    private RestTemplateHandheld restTemplateHandheld;

    @RequiresPermissions("handsetinfo:handsetinfo:view")
    @GetMapping()
    public String handsetinfo() {
        return prefix + "/handsetinfo";
    }

    /**
     * 查询手持机管理列表
     */
    @RequiresPermissions("handsetinfo:handsetinfo:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AHandsetInfo aHandsetInfo) {
        startPage();
        List<AHandsetInfo> list = aHandsetInfoService.selectAHandsetInfoList(aHandsetInfo);
        return getDataTable(list);
    }

    /**
     * 导出手持机管理列表
     */
    @RequiresPermissions("handsetinfo:handsetinfo:export")
    @Log(title = "手持机管理")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(String ids) throws Exception {
        List<AHandsetInfo> list = aHandsetInfoService.selectAHandsetInfoByIds(ids);

        //todo
        List<HandSetRequest> handSetRequests = new ArrayList<>();
        HandSetRequest handSetRequest;
        if (!CollectionUtils.isEmpty(list)) {
            for (AHandsetInfo handsetInfo : list) {
                handSetRequest = new HandSetRequest();
                handSetRequest.setDealerCode(handsetInfo.getDealerCode());
                handSetRequest.setDealerName(handsetInfo.getDealerName());
                handSetRequest.setImei(handsetInfo.getImei());
                handSetRequest.setSupplierCode(handsetInfo.getSupplierCode());
                handSetRequest.setSupplierName(handsetInfo.getSupplierName());
                handSetRequests.add(handSetRequest);
            }
        }
        String result = restTemplateHandheld.getResult(handSetRequests);

        //json转对象
        BaseOutput baseOutput = JSON.parseObject(result, BaseOutput.class);
        String code = baseOutput.getCode();
        String description = baseOutput.getDescription();

        if ("000000".equals(code)) {
            for (AHandsetInfo handsetInfo : list) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                handsetInfo.setImportXiandouTime(df.format(new Date()));
                handsetInfo.setStatus("已导出");
                aHandsetInfoService.updateAHandsetInfoByImei(handsetInfo);
            }
            return toAjax2(1, "导出成功！");
        } else {
            return toAjax2(0, description);
        }


    }

    /**
     * 新增手持机管理
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存手持机管理
     */
    @RequiresPermissions("handsetinfo:handsetinfo:add")
    @Log(title = "手持机管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AHandsetInfo aHandsetInfo) {
        return toAjax(aHandsetInfoService.insertAHandsetInfo(aHandsetInfo));
    }

    /**
     * 修改手持机管理
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        AHandsetInfo aHandsetInfo = aHandsetInfoService.selectAHandsetInfoById(id);
        mmap.put("aHandsetInfo", aHandsetInfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存手持机管理
     */
    @RequiresPermissions("handsetinfo:handsetinfo:edit")
    @Log(title = "手持机管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AHandsetInfo aHandsetInfo) {
        return toAjax(aHandsetInfoService.updateAHandsetInfo(aHandsetInfo));
    }

    /**
     * 删除手持机管理
     */
    @RequiresPermissions("handsetinfo:handsetinfo:remove")
    @Log(title = "手持机管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(aHandsetInfoService.deleteAHandsetInfoByIds(ids));
    }

    /**
     * 导入数据
     */
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<AHandsetInfo> util = new ExcelUtil<AHandsetInfo>(AHandsetInfo.class);
        List<AHandsetInfo> userList = util.importExcel(file.getInputStream());
        String message = importUser(userList, false);
        return AjaxResult.success(message);
    }

    private final static Map<Integer, AHandsetInfo> users = new LinkedHashMap<Integer, AHandsetInfo>();
    int q = 0;

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    public String importUser(List<AHandsetInfo> userList, Boolean isUpdateSupport) {
        users.clear();
        List<AHandsetInfo> userlist = aHandsetInfoService.selectAHandsetInfoList(null);
        for (int i = 1; i < users.size(); i++) {
            users.put(i, userlist.get(i));
        }


        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new BusinessExceptionZ("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (AHandsetInfo user : userList) {
            //导入的数据都能循环
            q++;
            System.out.println(q);
            //手持机imei号
            String imei = user.getImei();
            System.out.println("手持机imei编号：" + imei);
            try {
                //判断这个imei号是否在数据库存在
                AHandsetInfo aHandsetInfo = aHandsetInfoService.selectAHandsetInfoByImei(imei);

                if (aHandsetInfo == null) {
                    Integer userId = users.size() + 1;
                    user.setId(userId);
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    user.setImportExcelTime(df.format(new Date()));
                    user.setStatus("未导出");
                    users.put(userId, user);
                    aHandsetInfoService.insertAHandsetInfo(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、手持机 " + user.getImei() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、手持机 " + user.getImei() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、手持机 " + user.getImei() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessExceptionZ(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 下载模板
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<AHandsetInfo> util = new ExcelUtil<AHandsetInfo>(AHandsetInfo.class);
        return util.importTemplateExcel("手持机数据");
    }
}
